import React, { useState } from 'react'
import { NavBar, Button, Input, Toast, DatePicker } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { LeftOutline, SetOutline } from 'antd-mobile-icons'
import { archiveService } from '../../services/archiveService'
/**
 * 档案创建页面组件
 * 用于创建新的健康档案，包含基本信息录入和验证功能
 */
function Index() {
  // 导航钩子
  const navigate = useNavigate()
  // 表单数据状态
  const [formData, setFormData] = useState({
    relationship: '',      // 与用户的关系
    name: '',             // 姓名
    idCard: '',           // 身份证号
    birthDate: '',        // 出生日期           // 性别
    gender: '',
    phone: ''             // 联系电话
  })
  // 日期选择器显示状态
  const [datePickerVisible, setDatePickerVisible] = useState(false)
  /**
   * 返回上一页
   */
  const handleBack = () => {
    navigate('/health')
  }
  /**
   * 处理表单输入变化
   * @param field 表单字段名
   * @param value 新的值
   */
  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }
  /**
   * 处理日期选择
   * @param date 选择的日期对象
   */
  const handleDateSelect = (date: Date) => {
    const formattedDate = date.toLocaleDateString('zh-CN')
    setFormData(prev => ({
      ...prev,
      birthDate: formattedDate
    }))
    setDatePickerVisible(false)
  }
  /**
   * 处理表单提交
   * 验证必填字段并保存档案数据
   */
  const handleSubmit = () => {
    // 验证必填字段
    if (!formData.relationship || !formData.name || !formData.idCard || !formData.birthDate || !formData.gender || !formData.phone) {
      Toast.show({
        content: '请填写所有必填字段',
        position: 'center'
      })
      return
    }
    try {
      // 保存档案数据
      const newArchive = archiveService.addArchive({
        relationship: formData.relationship,
        name: formData.name,
        idCard: formData.idCard,
        birthDate: formData.birthDate,
        gender: formData.gender,
        phone: formData.phone
      })

      console.log('档案创建成功:', newArchive)
      
      Toast.show({
        content: '档案创建成功',
        position: 'center',
        icon: 'success'
      })

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        navigate('/health')
      }, 1500)
    } catch (error) {
      console.error('创建档案失败:', error)
      Toast.show({
        content: '创建档案失败，请重试',
        position: 'center'
      })
    }
  }

  // 关系选项配置
  const relationshipOptions = [
    { label: '本人', value: 'self' },
    { label: '配偶', value: 'spouse' },
    { label: '父母', value: 'parent' },
    { label: '子女', value: 'child' },
    { label: '亲戚', value: 'relative' },
    { label: '朋友', value: 'friend' }
  ]

  // 性别选项配置
  const genderOptions = [
    { label: '♂ 男', value: 'male' },
    { label: '♀ 女', value: 'female' }
  ]

  return (
    <div style={{ 
      backgroundColor: '#f5f5f5', 
      minHeight: '100vh',
      display: 'flex',
      flexDirection: 'column'
    }}>
      {/* 顶部导航栏 */}
      <NavBar 
        style={{ 
          backgroundColor: '#ffffff',
          borderBottom: '1px solid #e0e0e0'
        }}
        backArrow={false}
        left={
          <LeftOutline 
            style={{ 
              fontSize: '18px', 
              color: '#333',
              cursor: 'pointer'
            }}
            onClick={handleBack}
          />
        }
        right={
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '12px' 
          }}>
            <SetOutline style={{ fontSize: '16px', color: '#666' }} />
          </div>
        }
      >
        <span style={{ 
          fontSize: '18px', 
          fontWeight: '600',
          color: '#333'
        }}>
          新建档案
        </span>
      </NavBar>

      {/* 基本信息标签 */}
      <div style={{
        padding: '16px 20px 0 20px'
      }}>
        <div style={{
          backgroundColor: '#1890ff',
          color: '#ffffff',
          padding: '8px 16px',
          borderRadius: '20px',
          fontSize: '14px',
          fontWeight: '500',
          display: 'inline-block'
        }}>
          基本信息
        </div>
      </div>

      {/* 关系选择 */}
      <div style={{
        padding: '20px',
        backgroundColor: '#ffffff',
        margin: '16px 20px 0 20px',
        borderRadius: '12px'
      }}>
        <div style={{
          fontSize: '16px',
          fontWeight: '500',
          color: '#333',
          marginBottom: '16px'
        }}>
          与您的关系:
        </div>
        <div style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: '12px'
        }}>
          {relationshipOptions.map((option) => (
            <div
              key={option.value}
              onClick={() => handleInputChange('relationship', option.value)}
              style={{
                backgroundColor: formData.relationship === option.value ? '#1890ff' : '#f0f0f0',
                color: formData.relationship === option.value ? '#ffffff' : '#666',
                padding: '8px 16px',
                borderRadius: '20px',
                fontSize: '14px',
                cursor: 'pointer',
                transition: 'all 0.2s ease'
              }}
            >
              {option.label}
            </div>
          ))}
        </div>
      </div>

      {/* 表单字段 */}
      <div style={{
        padding: '20px',
        backgroundColor: '#ffffff',
        margin: '16px 20px 0 20px',
        borderRadius: '12px'
      }}>
        {/* 姓名 */}
        <div style={{ marginBottom: '20px' }}>
          <div style={{
            fontSize: '16px',
            fontWeight: '500',
            color: '#333',
            marginBottom: '8px'
          }}>
            <span style={{ color: '#ff4d4f' }}>*</span>姓名:
          </div>
          <Input
            placeholder="请输入真实姓名"
            value={formData.name}
            onChange={(value) => handleInputChange('name', value)}
            style={{
              backgroundColor: '#f8f9fa',
              border: '1px solid #e9ecef',
              borderRadius: '8px',
              padding: '12px'
            }}
          />
        </div>

        {/* 身份证 */}
        <div style={{ marginBottom: '20px' }}>
          <div style={{
            fontSize: '16px',
            fontWeight: '500',
            color: '#333',
            marginBottom: '8px'
          }}>
            <span style={{ color: '#ff4d4f' }}>*</span>身份证:
          </div>
          <Input
            placeholder="请输入身份证号码"
            value={formData.idCard}
            onChange={(value) => handleInputChange('idCard', value)}
            style={{
              backgroundColor: '#f8f9fa',
              border: '1px solid #e9ecef',
              borderRadius: '8px',
              padding: '12px'
            }}
          />
        </div>

        {/* 出生日期 */}
        <div style={{ marginBottom: '20px' }}>
          <div style={{
            fontSize: '16px',
            fontWeight: '500',
            color: '#333',
            marginBottom: '8px'
          }}>
            <span style={{ color: '#ff4d4f' }}>*</span>出生日期:
          </div>
          <div
            onClick={() => setDatePickerVisible(true)}
            style={{
              backgroundColor: '#f8f9fa',
              border: '1px solid #e9ecef',
              borderRadius: '8px',
              padding: '12px',
              cursor: 'pointer',
              color: formData.birthDate ? '#333' : '#999',
              minHeight: '20px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            {formData.birthDate || '请选择出生日期'}
          </div>
        </div>

        {/* 性别 */}
        <div style={{ marginBottom: '20px' }}>
          <div style={{
            fontSize: '16px',
            fontWeight: '500',
            color: '#333',
            marginBottom: '8px'
          }}>
            <span style={{ color: '#ff4d4f' }}>*</span>性别:
          </div>
          <div style={{
            display: 'flex',
            gap: '16px'
          }}>
            {genderOptions.map((option) => (
              <div
                key={option.value}
                onClick={() => handleInputChange('gender', option.value)}
                style={{
                  backgroundColor: formData.gender === option.value ? '#1890ff' : '#f0f0f0',
                  color: formData.gender === option.value ? '#ffffff' : '#666',
                  padding: '8px 16px',
                  borderRadius: '8px',
                  fontSize: '14px',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease'
                }}
              >
                {option.label}
              </div>
            ))}
          </div>
        </div>

        {/* 联系方式 */}
        <div style={{ marginBottom: '20px' }}>
          <div style={{
            fontSize: '16px',
            fontWeight: '500',
            color: '#333',
            marginBottom: '8px'
          }}>
            <span style={{ color: '#ff4d4f' }}>*</span>联系方式:
          </div>
          <Input
            placeholder="请输入手机号码"
            value={formData.phone}
            onChange={(value) => handleInputChange('phone', value)}
            style={{
              backgroundColor: '#f8f9fa',
              border: '1px solid #e9ecef',
              borderRadius: '8px',
              padding: '12px'
            }}
          />
        </div>
      </div>

      {/* 底部保存按钮 */}
      <div style={{
        padding: '20px',
        backgroundColor: '#ffffff',
        margin: '16px 20px 20px 20px',
        borderRadius: '12px'
      }}>
        <Button
          style={{
            width: '100%',
            height: '48px',
            borderRadius: '24px',
            backgroundColor: '#1890ff',
            border: 'none',
            fontSize: '16px',
            fontWeight: '600',
            color: '#ffffff'
          }}
          onClick={handleSubmit}
        >
          保存
        </Button>
      </div>

      {/* 日期选择器 */}
      <DatePicker
        visible={datePickerVisible}
        onClose={() => setDatePickerVisible(false)}
        onConfirm={handleDateSelect}
        title="选择出生日期"
        precision="day"
        max={new Date()}
        min={new Date('1900-01-01')}
      />
    </div>
  )
}

export default Index
